package cn.itcast.service;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisConstant;
import cn.itcast.entity.Result;
import cn.itcast.utils.SMSUtils;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    public Result sendLoginCode(String phone) {

        // 随机生成验证码
        String code = RandomUtils.nextInt(100000, 999999) + "";

        log.info("获取到的手机号验证码为： {}",code);

        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phone,code);
            String redisKey = "LOGIN_" + phone;
            this.redisTemplate.opsForValue().set(redisKey,code,Duration.ofMinutes(5));

            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS,code);
        } catch (ClientException e) {
            log.error("发送短信给用户失败",e);
        }
        return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
    }
}
